<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <!-- 自定义单元格 -->
      <template slot-scope="{ row }" slot="area">
        <p>{{ getAreasName(row.area) }}</p>
      </template>

      <template slot-scope="{ row }" slot="user">
        <p>{{ row.cycling.user.nickname }}</p>
      </template>
      <template slot-scope="{ row }" slot="max_speed">
        <p>{{ row.cycling.max_speed }}</p>
      </template>
      <template slot-scope="{ row }" slot="avg_speed">
        <p>{{ row.cycling.avg_speed }}</p>
      </template>
      <template slot-scope="{ row }" slot="distance">
        <p>{{ row.cycling.distance }}</p>
      </template>
      <template slot-scope="{ row }" slot="duration">
        <p>{{ row.cycling.duration }}</p>
      </template>
      <template slot-scope="{ row }" slot="calories">
        <p>{{ row.cycling.calories }}</p>
      </template>
      <template slot-scope="{ row }" slot="status">
        <p>{{ row.cycling.status_text }}</p>
      </template>
      <!-- 自定义操作列 -->
      <template #menu="{ row, index, size }">
        <el-tooltip class="item" effect="dark" content="关于更多" placement="top">
          <el-button type="primary" :size="'mini'" icon="el-icon-more" @click="handleMore(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
        </el-tooltip>
      </template>
    </avue-crud>
    <!-- 弹窗 -->
    <el-dialog :visible.sync="isShowMoreTableModal" append-to-body destroy-on-close title="关于更多" width="60%">
      <avue-tabs :option="tabOption" @change="handleTabChange"></avue-tabs>
      <div v-if="tabType.prop === 'tab1'">
        <avue-crud :option="thumbOption" :data="thumbData"></avue-crud>
      </div>
      <div v-else-if="tabType.prop === 'tab2'">
        <avue-crud :option="followsOption" :data="followsData">
          <template slot-scope="{ row }" slot="nickname">
            <p>{{ row }}</p>
          </template>
        </avue-crud>
      </div>
      <div v-else-if="tabType.prop === 'tab3'">
        <avue-crud :option="commentsOption" :data="commentsData"></avue-crud>
      </div>
      <div v-else-if="tabType.prop === 'tab4'">
        <avue-crud :option="rankOption" :data="rankData" :page.sync="rankPage" @current-change="currentRideRankChange" @size-change="sizeRideRankChange" @on-load="getRideRankList"></avue-crud>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="close()"> 取消 </el-button>
        <el-button type="primary" @click="close()"> 确认 </el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { getCyclingRoutePageList, getCyclingRouteLikesList, getCyclingRouteFollowsList, getCyclingRouteCommentsList, getCyclingRouteRankList } from "./api/cyclingRoute";
import { getSystemUserList } from "../systemManage/systemUserManage/api/user";
import { getAreasList } from "@/api/common";
import { mapGetters } from "vuex";
import website from "@/config/website";
import { getAddressByCode } from "@/util/util";
export default {
  data() {
    return {
      currentRideItem: {},
      tabType: {},
      tabOption: {
        column: [{
          icon: 'el-icon-thumb',
          label: '点赞列表',
          prop: 'tab1',
        }, {
          icon: 'el-icon-star-off',
          label: '关注列表',
          prop: 'tab2',
        }, {
          icon: 'el-icon-chat-line-square',
          label: '评论列表',
          prop: 'tab3',
        }, {
          icon: 'el-icon-rank',
          label: '骑行排名列表',
          prop: 'tab4',
        }]
      },
      isShowMoreTableModal: false,
      thumbData: [],
      thumbOption: {
        menu: false,
        menuType: 'button',
        // height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项 提示语
        searchShow: false,
        searchMenuSpan: 6,
        border: false,

        index: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        column: [
          {
            label: "昵称",
            prop: "nickname",
          },
          {
            label: "联系电话",
            prop: "phone",
          },
        ],
      },
      followsData: [],
      followsOption: {
        menu: false,
        menuType: 'button',
        // height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项 提示语
        searchShow: false,
        searchMenuSpan: 6,
        border: false,

        index: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        column: [
          {
            label: "昵称",
            prop: "nickname",
          },
          {
            label: "头像",
            prop: "profile_picture",
            type: "upload",
            clearable: true,
            loadText: '头像上传中，请稍等',
            listType: "picture-card",
            action: "/admin/common/upload",
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            dataType: "array",
          },
          {
            label: "联系电话",
            prop: "phone",
          },
        ],
      },
      commentsData: [],
      commentsOption: {
        menu: false,
        menuType: 'button',
        // height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项 提示语
        searchShow: false,
        searchMenuSpan: 6,
        border: false,

        index: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        column: [
          {
            label: "用户",
            prop: "nickname",
            slot: true,
          },
          {
            label: "内容",
            prop: "content",
            type: 'textarea',
          },
        ],
      },
      rankData: [],
      rankPage: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      rankOption: {
        menu: false,
        menuType: 'button',
        // height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项 提示语
        searchShow: false,
        searchMenuSpan: 6,
        border: false,

        index: false,
        viewBtn: false,
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        column: [
          {
            label: "昵称",
            prop: "nickname",
          },
           {
            label: "最大速度(km/h)",
            prop: "max_speed",
          },
          {
            label: "平均速度(km/h)",
            prop: "avg_speed",
          },

          {
            label: "骑行距离",
            prop: "distance",
          },

          {
            label: "总运动时长(秒)",
            prop: "duration",
          },
          {
            label: "消耗千卡",
            prop: "calories",
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            dicData: [{
              label: '进行中',
              value: 0
            }, {
              label: '暂停',
              value: 1
            }, {
              label: '结束',
              value: 2
            }],
          },
        ],
      },
      addressData: [],
      form: {},
      query: {},
      loading: true,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menu: true,
        menuType: 'button',
        height: "auto",
        calcHeight: 30,
        tip: false, // 当前表格已选择多少项数据 提示语
        searchShow: true,
        searchMenuSpan: 6,
        border: false,

        index: true,
        indexLabel: '序号',
        editBtn: false,
        selection: false,
        dialogClickModal: false,
        addBtn: false,
        delBtn: false,
        column: [
          {
            label: "名称",
            prop: "name",
            search: true,
          },
          {
            label: "用户",
            prop: "nickname",
            type: 'select',
            search: true,
            hide: true, //表格是否显示该字段（该字段的列）
            display: false, //弹出的表单是否显
            dicData: [],
          },

          {
            label: "行政区域",
            prop: "area",
            type: "cascader",
            checkStrictly: true,
            props: {
              label: 'name',
              value: 'code',

            },
            dicData: [],
            search: true
          },
          {
            label: "骑行人",
            prop: "user",
          },
          {
            label: "最大速度(km/h)",
            prop: "max_speed",
          },
          {
            label: "平均速度(km/h)",
            prop: "avg_speed",
          },

          {
            label: "骑行距离",
            prop: "distance",
          },

          {
            label: "总运动时长(秒)",
            prop: "duration",
          },
          {
            label: "消耗千卡",
            prop: "calories",
          },
          {
            label: "状态",
            prop: "status",
            type: 'select',
            dicData: [{
              label: '进行中',
              value: 0
            }, {
              label: '暂停',
              value: 1
            }, {
              label: '结束',
              value: 2
            }],
          },
        ],
      },
      data: [],
      userInfo: {}
    };
  },

  computed: {
    ...mapGetters(["permission"]),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.account_id);
      });
      return JSON.stringify(ids);
    },
  },
  created() {
    const user = localStorage.getItem(website.key + "-user");
    if (user) this.userInfo = JSON.parse(user);
    this.getUserData()
    this.getAreasData()
    this.tabType = this.tabOption.column[0];
  },
  mounted() { },
  methods: {
    close() { 
      this.tabType = {}
      this.isShowMoreTableModal = false
    },
    handleTabChange(column) {
      this.tabType = column
      if (column.prop === 'tab1') {
        this.getThumbList()
      }
      if (column.prop === 'tab2') {
        this.getFollowsList()
      }
      if (column.prop === 'tab3') {
        this.getCommentsList()
      }
      if (column.prop === 'tab4') {
        this.getRideRankList(this.rankPage)
      }
    },
    handleMore(row, index) {
      this.currentRideItem = row
      this.isShowMoreTableModal = true
      this.getThumbList()
    },
    getThumbList() {
      getCyclingRouteLikesList({ post_id: this.currentRideItem.id }).then((res) => {
        console.log('点赞列表：', res.data.list);
        this.thumbData = res.data.list || [];
      });
    },
    getFollowsList() {
      getCyclingRouteFollowsList({ post_id: this.currentRideItem.id }).then((res) => {
        console.log('关注列表：', res.data.list);
        res.data.list && res.data.list.forEach(item => {
          item.nickname = item.user.nickname
          item.phone = item.user.phone
          item.profile_picture = item.user.profile_picture
        });
        this.followsData = res.data.list || [];
      });
    },
    getCommentsList() {
      getCyclingRouteCommentsList({ post_id: this.currentRideItem.id }).then((res) => {
        console.log('评论列表：', res.data);
        res.data && res.data.forEach(item => {
          item.nickname = item.user.nickname
        });
        this.commentsData = res.data

      });
    },
    getRideRankList(page) {
      console.log(page);
      getCyclingRouteRankList({ 
        post_id: this.currentRideItem.id,
        page: page.currentPage,
        size: page.pageSize}).then((res) => {
        console.log('排行榜列表：', res.data.list);
        this.rankData = res.data.list || [];
        this.rankPage.total = res.data.total
      });
    },
    currentRideRankChange(page_cursor) {
      this.rankPage.currentPage = page_cursor;
    },
    sizeRideRankChange(page_size) {
      this.rankPage.pageSize = page_size;
    },
    // 根据code 查找 name
    getAreasName(code) {
      if (typeof code === 'object' && code !== null) {
        return getAddressByCode(code.code, this.addressData)
      }
      return getAddressByCode(code, this.addressData)
    },
    // 获取行政区域
    getAreasData() {
      getAreasList({}).then((res) => {
        this.addressData = res.data || [];
        this.option.column[2].dicData = res.data || [];
      });
    },
    // 获取用户
    getUserData() {
      getSystemUserList({
        "page": 1,
        "size": 999999
      }).then((res) => {
        const resData = res.data.list;
        this.option.column[0].dicData = resData.map((r, index) => {
          return {
            label: r.nickname,
            value: r.id
          }
        })
      });
    },
    rowView(row, index) {
      this.$refs.crud.rowView(row, index);
    },
    rowEdit(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },
    rowDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    rowSave(row, done, loading) {
      return
      let param = {
        uid: this.userInfo.id,
        ...row
      }
      xxx(param).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      return
      let params = {
        "uid": this.userInfo.id,
        ...row
      }
      if (typeof row.province === 'object' && row.province !== null) {
        params.province = row.province.code
      }
      if (typeof row.city === 'object' && row.city !== null) {
        params.city = row.city.code
      }
      if (typeof row.area === 'object' && row.area !== null) {
        params.area = row.area.code
      }
      xxx(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      return
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return xxx({ id: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },



    beforeOpen(done, type) {

      done();
    },

    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.area) {
        params.province = params.area[0]
        params.city = params.area[1]
        params.area = params.area[2]
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(page_cursor) {
      this.page.currentPage = page_cursor;
    },
    sizeChange(page_size) {
      this.page.pageSize = page_size;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      let param = {
        ...params,
        page: page.currentPage,
        size: page.pageSize
      }
      getCyclingRoutePageList(param).then((res) => {
        const resData = res.data;
        this.page.total = resData.total;
        this.data = resData.list;
        this.loading = false;
        this.selectionClear();
      });
    },


    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
};
</script>


<style lang="scss" scoped></style>